<?php
class db_messages
{
	function __construct()
	{
		Global $mySql, $lib;
		$this->mySql = $mySql;
		$this->lib = $lib;	
	}
	public function getFeed($Login)
	{
		/* To Create a Custom Feed 
			1. Grab User Prefrences
			2. Create MySQL Statement
		*/
			// Set The User Prefrences Variable
			$prefs = $Login['prefs']['display'];
			// 1) SELECT Statement that Defines all Fields
			$sql = "SELECT msg.Tbl_ID, msg.User_ID, msg.Message, msg.OrgAuth, msg.Active, msg.Time_TS, msg.Rating, vote.Vote_TS, follow.Follow_ID, follow.Action";
			
				// a) Add the Reply Fields
				$sql .= ", reply.Msg_ID as Reply_ID";
			
			// 3) Add the FROM Statement
			$sql .= " FROM messages msg";
			
			
			$statement = " LEFT JOIN replies reply ON msg.Tbl_ID = reply.Msg_ID AND reply.User_ID = %d";
			
			// b) Inject the Proper Fields
			$sql .= sprintf($statement,
							mysql_real_escape_string($Login['login']['id']));
			
			// 6) LEFT JOIN the Vote Table 
				// The Vote Table is Always Joined. If not, it would allow users to vote on an entry twice, if not more
			$statement = " LEFT JOIN vote ON msg.Tbl_ID = vote.Msg_ID AND vote.User_ID = %d";
				$sql .= sprintf($statement,
							mysql_real_escape_string($Login['login']['id']));
			
			// 7) LEFT JOIN the Follow Table
				// The Follow Table is Always Joined to allow the 'WHERE' statement to filter out any Users that are Blocked
			$statement = " LEFT JOIN follow ON msg.User_ID = follow.Follow_ID AND follow.User_ID = %d";
			$sql .= sprintf($statement,
							mysql_real_escape_string($Login['login']['id']));
						
			// 8) Add the Beginning WHERE Statement
			$statement = " WHERE follow.Action != -1"; // This will filter out any user that is blocked
			
			// 9) Check if 'Home' is the only feed selected
			if($prefs['Home'] && !$prefs['Reply'] && !$prefs['Everyone'])
			{
				// a) Filter out any record that does the user is not following
					// Because any user that is blocked has been filtered out at the begining, this only leaves the users that are followed
				$statement .= " AND follow.Action IS NOT NULL";
			}
			
			// 9b) Check if Home is Selected and Everyone is Not
			elseif($prefs['Home'] && !$prefs['Everyone'])
			{
				// a) Filter out any Record that the user doesn't follow
				$statement .= " AND follow.Action IS NOT NULL";
			}
			// 9c) Deafult: Meaning Everyone is selected
			else
			{
				// a) Include records that the user doesn't follow
				$statement .= " OR follow.Action IS NULL";
			}
			
			// 10) Check if the Reply Option is Selected
			if($prefs['Reply'])
			{
				// a) Include Records that have a reply.Msg_ID
					// This is only nessicary with Home and Reply are the only ones selected
				$statement .= " OR reply.Msg_ID IS NOT NULL";
			}
			$sql .= $statement;		
			if($prefs['Everyone'] == true ||$prefs['Reply'] == true || $prefs['Home'] == true)
			{
				$result = $this->mySql->makeQuery($sql);
				
			$this->mySql->listErrors();
			$num = 1;		
			// Data Sorting
			while($temp = mysqli_fetch_array($result))
			{
				$data[$num]['Tbl_ID'] = $temp['Tbl_ID'];
				$data[$num]['User_ID'] = $temp['User_ID'];
				$data[$num]['Message'] = $temp['Message'];
				$data[$num]['OrgAuth'] = $temp['OrgAuth'];
				$data[$num]['Active'] = $temp['Active'];
				$data[$num]['Time_TS'] = $temp['Time_TS'];
				$data[$num]['Rating'] = $temp['Rating'];
				$data[$num]['Vote_TS'] = $temp['Vote_TS'];
				$data[$num]['Reply_ID'] = $temp['Reply_ID'];
				if($prefs['Home']){ $data[$num]['Follow_ID'] = $temp['Follow_ID']; }
				$data[$num]['Action'] = $temp['Action'];
				$num++;
			}
			$this->lastRequest['data'] = $data;
			$this->lastRequest['length'] = $num - 1;
			$this->lastRequest['query'] = $sql;
			return $data;
			}
			else
			{
				echo $sql;
				return false;
			}
	}
	function getUserFeed($info) // This is a specific User's Feed
	{
		$sql =  "SELECT msg.Tbl_ID, msg.User_ID, msg.Message, msg.OrgAuth, msg.Active, msg.Time_TS, msg.Rating, vote.Vote_TS
					FROM messages msg
					LEFT JOIN vote ON msg.Tbl_ID = vote.Msg_ID AND vote.User_ID = %d 
					WHERE msg.User_ID = %d
					ORDER BY Time_TS DESC
					LIMIT 0,20";
			$query = sprintf($sql,
				mysql_real_escape_string($info[loginid]),
				mysql_real_escape_string($info[userid]));
		$result = $this->mySql->makeQuery($query);
		$num = 1;
		while($temp = mysql_fetch_array($result))
		{
			$data[$num]['Tbl_ID'] = $temp['Tbl_ID'];
			$data[$num]['User_ID'] = $temp['User_ID'];
			$data[$num]['Message'] = $temp['Message'];
			$data[$num]['OrgAuth'] = $temp['OrgAuth'];
			$data[$num]['Active'] = $temp['Active'];
			$data[$num]['Time_TS'] = $temp['Time_TS'];
			$data[$num]['Rating'] = $temp['Rating'];
			$data[$num]['Vote_TS'] = $temp['Vote_TS'];
			$num++;
		}
		$this->lastRequest[data] = $data;
		$this->lastRequest[length] = $num - 1;
		$this->lastRequest[query] = $query;
		$this->mySql->listErrors();
		return $data;
	}
	function getUserPrefrences()
	{
		
	}
	function insertMessage($form)
	{
		$userid = $form[id];
		$message = $form[message];
		$data = $this->findReplies($message);
		$orgauth = $this->lib->findUserNamebyID($userid);
		$ipaddress = $_SERVER["REMOTE_ADDR"];
		if(!EMPTY($userid) && !EMPTY($message) && !EMPTY($orgauth))
		{
			$sql = "INSERT INTO messages (User_ID, Message, OrgAuth, IP_Addr) VALUES ('%s','%s','%s','%s')";
			$query = sprintf($sql,
	            mysql_real_escape_string($userid),
	            mysql_real_escape_string($message),
				mysql_real_escape_string($orgauth),
				mysql_real_escape_string($ipaddress),
				mysql_real_escape_string($reply));
			$this->mySql->makeQuery($query);
		}
		else
		{
			return false;
		}
		$id = mysql_insert_id();
		if(!EMPTY($data[users]))
		{
			$this->insertReplyList($data[users], $id);
		}
		if(!$this->mySql->listErrors())
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	function insertReplyList($data, $msgid)
	{
		$sql = $this->buildNameList($data);
		$result = $this->mySql->makeQuery($sql);
		$idList = Array();
		while($temp = mysql_fetch_array($result))
		{	
			$idList[] = $temp[Tbl_ID];
		}
		print_r($idList);
		foreach($idList as $key => $foreachid)
		{
			$sql = "INSERT INTO replies (Msg_ID, User_ID) VALUES (%d,%d)";
			$query = sprintf($sql,
	            mysql_real_escape_string($msgid),
	            mysql_real_escape_string($foreachid));
			$this->mySql->makeQuery($query);
		}
	}
	function buildNameList($name)
	{
		$sql = "SELECT *"; 
        $sql .= " FROM users"; 
		foreach($name as $key => $data)
		{
		  if (!EMPTY($data)) 
           { 
                $search[] = sprintf(" Username='%s' ", mysql_real_escape_string($data)); 
           } 
		 }
           if (TRUE != empty($search)) 
           { 
                foreach ($search as $key => $string) 
                { 
                     if (0 === $key) 
                     { 
                          $sql .= " WHERE"; 
                     } 
                     if (0 < $key) 
                     { 
                          $sql .= " OR"; 
                     } 
                     $sql .= " ".$string; 
                } 
           }
		   else
		   {
			unset($sql);
		   }
		echo $sql;
	   return $sql;
		
	}
	function findReplies($data)
	{
		$data = $data . " ";
		$temp = explode("@", $data);
		foreach ($temp as $key => $message)
		{
			if($key != 0)
			{
				$string = substr($message, 0, strpos($message," "));
				$return[users][] = substr($string, 0, strlen($data));
			}
		}
		print_r($return[users]);
		$return[message] = $data;
		return $return;
	}
}